package multiThreading.Account;

public class account extends Thread{
    private String no;//用户名
    private double base;//账号里的本金
    private boolean flag=false;//作为账户里有无钱的标志
    public account(String no,String name,double base){
        super(name);
        this.no=no;
        this.base=base;
    }
    public void getMoney(double money){
        //进行取钱操作
        synchronized(this){
            if(!flag){//如果里面没有钱的话就暂停当前线程
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            else{
                System.out.println("账号"+this.no+"从账户中取出："+money);
                this.base-=money;
                System.out.println("账号"+this.no+"余额还有："+this.base);
                flag=false;
                try {
                    sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                notifyAll();
            }
        }
    }
    public void saveMoney(double money){
        //进行存钱操作
        synchronized(this){
            if(flag){//如果里面有钱的话就暂停当前线程
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            else{
                System.out.println("账号"+this.no+"向账户中存入："+money);
                this.base+=money;
                System.out.println("账号"+this.no+"余额还有："+this.base);
                flag=true;
                try {
                    sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                notifyAll();
            }
        }
    }
}
